<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/12/24 0024
  Time: 8:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用Ajax向服务器发送请求</title>
    <link rel="shortcut icon" href="images/bg.ico" type="image/x-icon" />
</head>
<body>

<div id="hb" style="width: 300px;height: 200px;border:1px solid cyan;"></div>

<script type="text/javascript">
    /*
    初始化XMLHTTPRequest对象
    */
    var xhp;
    var test=function () {
        if(window.XMLHttpRequest){
            xhp=new XMLHttpRequest();
            console.log("创建成功")
        }else{
            try{
                xhp=new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e){
                xhp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
    }
    test();//执行创建XMLHttpRequest对象的函数
    /*为该对象指定一个返回处理函数*/
    var resultset=function(a){
        console.log(a);
    }
    xhp.onreadystatechange=function () {
        resultset(3);
    }

    /*创建一个与服务器的连接*/


    //在地址后面加上时间戳使数据能实时刷新
    var sendObject1="receive.jsp?nocache="+new Date().getTime();
    var sendObject2="xmlResponse?nocache="+new Date().getTime();
    xhp.open("post",sendObject2,false);//指定当前的连接方式

    /*设置正确的请求头*/
    xhp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

    /*向服务器发送连接*/
    var param="post连接的参数";
    xhp.send(param);


    // 处理服务器响应

    /*字符串响应*/
    function getResult() {
        if(xhp.readyState==4){
            console.log("请求完成")
            if(xhp.status==200){
                console.log("请求成功")
                var div=document.getElementById('hb');
                div.innerHTML=xhp.responseText;
                alert(xhp.responseText);
                console.log(xhp.responseText);
            }else{
                alert("页面错误!"+xhp.status);
            }
        }
    }
    getResult();

    //处理XML响应
    function getResult2() {
        if(xhp.readyState==4){
            console.log("xml文件请求完毕")
            if(xhp.status==200){
                console.log("xml文件请求成功")
                var xmls=xhp.responseXML;
                var str="";
                for(var index=0;index<xmls.getElementsByTagName("book").length;index++){
                    var book=xmls.getElementsByTagName("book")[index];
                    str=str+"这本"+book.getElementsByTagName("bookName")[0].firstChild.data+'是由'+
                        book.getElementsByTagName("author")[0].firstChild.data+"所写<br>";
                }
                document.write(str);
            }
        }
    }
    getResult2();



</script>

</body>
</html>
